<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('usuario_model', '', TRUE);
        $this->load->model('horario_model', '', TRUE);
    }

    function index() {
        //This method will have the credentials validation
        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

        if ($this->form_validation->run() == FALSE) {
           
             $this->load->view('templates/head');
            $this->load->view('templates/header_login');
            $this->load->view('login_view');
            $this->load->view('templates/footer_login');
        } else {
            //Go to private area
            redirect('home', 'refresh');
        }
    }

    function check_database($password) {
        //Field validation succeeded.  Validate against database
        $username = $this->input->post('username');

        //query the database
        $result = $this->usuario_model->login($username, $password);
        if ($result) {
            foreach ($result as $row)
             {
                $this->session->set_userdata('jefe', $row['jefe']);
                $this->session->set_userdata('id', $row['cedula'] );
                $this->session->set_userdata('username', $row['nombre'].' '.$row['apellidos']);
                $this->session->set_userdata('tipo', $row['tipo']);
                $this->session->set_userdata('departamento', $row['departamento']);
                $this->session->set_userdata('puesto', $row['puesto']);
                $this->session->set_userdata('ubicacion', $row['ubicacion']);
                $this->session->set_userdata('telefono', $row['telefono']);
                $this->session->set_userdata('logged_in', 1);
                $horario = $row['horario'];
             }
             
              $hor = $this->horario_model->get($horario);
              if ($hor <> NULL) {
                            foreach ($hor->result() as $record) {
                                $horarioFinal =  $record->nombre.': '.$record->entrada.' ~ '.$record->salida;
                            }
                    }
            $this->session->set_userdata('horario',$horarioFinal);
             return true;
        }else {
            $this->form_validation->set_message('check_database', 'Nombre de Usuario o contraseña incorrecto');
            return false;
        }
    }

}

?>